<?php

namespace App\Http\Controllers;

use App\Models\Referral;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Plan;
use Filament\Notifications\Notification;
use Yansongda\Pay\Pay;
use App\Models\Balance;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Coupon;
class OrderController extends Controller
{

    protected $payment_method;
    protected $plan_id;
    protected $coupon_code;
    protected $price;
    protected $renew;
    protected $upgrade;

    protected $order_id;
    protected $plan_name;
    protected $plan_duration;
    protected $remark;

    public function __construct($plan_id, $payment_method, $remark, $coupon_code = null, $renew = false, $upgrade = false)
    {
        $this->plan_id = $plan_id;
        $this->renew = $renew;
        $this->upgrade = $upgrade;
        $this->payment_method = $payment_method;
        $this->coupon_code = $coupon_code;
        $this->plan_name = Plan::find($this->plan_id)->name;
        $this->plan_duration = Plan::find($this->plan_id)->duration;

        if($this->coupon_code){
            $this->price = $this->subtractCouponAmount();
        }else{
            $this->price = Plan::find($this->plan_id)->price;
        }
        $this->order_id = date('YmdHis').Filament::auth()->id().rand(1000,9999);
        if($this->payment_method == "balance"){
            $this->payUsingUserBalance();
            updateReferralCommission($this->plan_id, $this->order_id, Filament::auth()->user()->referred_by);
        }

        if($this->payment_method == 'alipay'){
            $this->payUsingAlipay();
        }
    }

    function createOrder() {
        return Order::create([
            'order_id' => $this->order_id,
            'user_id' => Filament::auth()->id(),
            'plan_id' => $this->plan_id,
            'payment_method' => $this->payment_method,
            'amount' => $this->price,
            'paid_at' => now()->toDateTimeString(),
            'status' => 'completed',
            'remark' => $this->remark,
        ]);
    }

    function payUsingAlipay() {
        return redirect()->route('alipay', ['price' => $this->price, 'plan_name' => $this->plan_name, 'order_id' => $this->order_id]);
    }

    /**
     * if using balance to pay for the plan
     */
    function payUsingUserBalance() {
        if(Filament::auth()->user()->balance < $this->price){
            return Notification::make()->title('用户余额不足')
                ->icon('heroicon-o-exclamation-circle')
                ->iconColor('red')
                ->color('red')
                ->send();
        }else{
            $current_user = Filament::auth()->getUser();
            $remaining_balance = $current_user->balance - $this->price;
            $plan_expired_at = $current_user->plan_expired_at;
            $referred_by = $current_user->referred_by;
            if($plan_expired_at && $this->renew){
                $plan_expired_at = Carbon::parse($plan_expired_at)->addDays($this->plan_duration);
            }else{
                $plan_expired_at = Carbon::now()->addDays($this->plan_duration);
            }
            Filament::auth()->user()->update(
                [
                    'balance' => $remaining_balance,
                    'plan_id' => $this->plan_id,
                    'plan_expired_at' => $plan_expired_at
                ]
            );

            $this->updateBalanceHistory();

            if($referred_by){
                updateReferralCommission($this->plan_id, $this->order_id, $referred_by);
            }

            return Notification::make()->title('购买会员成功')
                ->success()
                ->icon('heroicon-o-check-circle')
                ->iconColor('green')
                ->color('green')
                ->send();
        }
    }

    function updateBalanceHistory()
    {
        $balance = new Balance();
        $balance->user_id = Filament::auth()->id();
        $balance->order_id = $this->createOrder()->id;
        $balance->balance_after = Filament::auth()->user()->balance;
        $balance->balance_before = Filament::auth()->user()->balance + $this->price;
        $balance->type = 'buy_plan';
        $balance->save();
    }

    function subtractCouponAmount() {
        $coupon = Coupon::where('code', $this->coupon_code)->first();
        if($coupon && $coupon->expired_at > Carbon::now()){
            return Plan::find($this->plan_id)->price - $coupon->amount;
        }else{
            return $this->price;
        }
    }

}
